package com.jzo2o.customer.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.customer.mapper.AgencyWaarmerkingMapper;
import com.jzo2o.customer.model.domain.AgencyCertification;
import com.jzo2o.customer.model.domain.AgencyCertificationAudit;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditAddReqDTO;
import com.jzo2o.customer.service.AgencyWaarmerkingService;
import com.jzo2o.customer.service.IAgencyCertificationAuditService;
import com.jzo2o.mvc.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *
 * @Author mr.luo
 * @Date 01 7月 2025 19:47
 */
@Slf4j
@Service
public class AgencyWaarmerkingServiceImpl extends ServiceImpl<AgencyWaarmerkingMapper, AgencyCertification> implements AgencyWaarmerkingService {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private IAgencyCertificationAuditService agencyCertificationAuditService;

    /**
     * 服务人员认证申请
     *
     * @param dto
     */
    @Override
    public void workerCertificationAudit(AgencyCertificationAuditAddReqDTO dto) {

        // 根据身份证号和相关信息查询是否已存在认证记录
        AgencyCertificationAudit existingCertification = agencyCertificationAuditService.lambdaQuery()
                .eq(AgencyCertificationAudit::getIdNumber, dto.getIdNumber())
                .eq(AgencyCertificationAudit::getName, dto.getName())
                .eq(AgencyCertificationAudit::getLegalPersonIdCardNo, dto.getLegalPersonIdCardNo())
                .one();

        // 检查现有认证状态
        if (existingCertification != null) {
            int status = existingCertification.getCertificationStatus();
            if (status == 2) {
                throw new CommonException("当前公司已认证，无需重复申请");
            }
            if (status == 1) {
                throw new CommonException("认证申请正在处理中，请耐心等待");
            }
            if (status == 3) {
                // 处理已拒绝的情况 - 删除旧记录
                agencyCertificationAuditService.removeById(existingCertification.getId());
            }
        }

        // 创建新的认证申请
        AgencyCertificationAudit newCertification = new AgencyCertificationAudit();
        BeanUtils.copyProperties(dto, newCertification);

        // 设置申请人ID和默认状态
        newCertification.setServeProviderId(UserContext.currentUserId());
        newCertification.setCertificationStatus(1); // 认证中
        newCertification.setAuditStatus(1);
//        newCertification.setName(UserContext.currentUser().getName());
        newCertification.setAuditorName(UserContext.currentUser().getName());

        // 保存新申请
        boolean success = agencyCertificationAuditService.save(newCertification);
        if (!success) {
            throw new CommonException("提交认证申请失败");
        }
    }


    /**
     * 获取最新的驳回原因
     *
     * @return 包含驳回原因的Map
     * @throws CommonException 如果未申请认证、认证成功或认证中
     */
    @Override
    public Map<String, String> rejectReason() {
        // 查询最新的一条数据
        Long workId = UserContext.currentUserId();
        AgencyCertificationAudit latestRecord = agencyCertificationAuditService
                .lambdaQuery()
                .eq(AgencyCertificationAudit::getServeProviderId, workId)
                .orderByDesc(AgencyCertificationAudit::getAuditTime)
                .last("LIMIT 1")
                .one();

        // 检查记录是否存在
        if (latestRecord == null) {
            throw new CommonException("请先申请认证");
        }

        // 获取认证状态
        int status = latestRecord.getCertificationStatus();

        // 根据状态进行处理
        switch (status) {
            case 0:
                throw new CommonException("请先提交认证申请");
            case 1:
                throw new CommonException("认证申请正在处理中，请耐心等待");
            case 2:
                throw new CommonException("您已认证成功，无需查看驳回原因");
            case 3: // 假设3是"已驳回"状态
                // 确保驳回原因不为空
                String reason = latestRecord.getRejectReason();
                if (reason == null || reason.trim().isEmpty()) {
                    reason = "未提供具体驳回原因";
                }
                Map<String, String> result = new HashMap<>();
                result.put("rejectReason", reason);
                return result;
            default:
                // 处理其他未知状态
                throw new CommonException("未知认证状态: " + status);
        }
    }
}
